const express = require('express');
const router = express.Router();
const db = require('../config/db');
const upload = require('../middleware/upload');
const { isAdmin } = require('../middleware/roles');

// 获取商品列表
router.get('/products', (req, res) => {
  db.query('SELECT * FROM products ORDER BY created_at DESC', (error, results) => {
    if (error) {
      return res.status(500).json({ error: error.message });
    }
    res.json(results);
  });
});

// 获取单个商品
router.get('/products/:id', (req, res) => {
  const { id } = req.params;
  db.query('SELECT * FROM products WHERE id = ?', [id], (error, results) => {
    if (error) {
      return res.status(500).json({ error: error.message });
    }
    if (results.length === 0) {
      return res.status(404).json({ message: '商品不存在' });
    }
    res.json(results[0]);
  });
});

// 创建商品（需要管理员权限）
router.post('/products', isAdmin, upload.single('image'), async (req, res) => {
  try {
    const { title, description, price, category_id } = req.body;
    let image_url = null;

    // 如果上传了图片
    if (req.file) {
      image_url = `/uploads/${req.file.filename}`;
    }

    // 基本验证
    if (!title || !price) {
      return res.status(400).json({
        success: false,
        error: '标题和价格为必填项',
        code: 400
      });
    }

    // 检查分类是否存在
    if (category_id) {
      const [category] = await db.promise().query(
        'SELECT id FROM product_categories WHERE id = ?',
        [category_id]
      );
      if (category.length === 0) {
        return res.status(400).json({
          success: false,
          error: '分类不存在',
          code: 400
        });
      }
    }

    const [result] = await db.promise().query(
      'INSERT INTO products (title, description, price, category_id, image_url) VALUES (?, ?, ?, ?, ?)',
      [title, description, price, category_id, image_url]
    );

    res.json({
      success: true,
      data: {
        id: result.insertId,
        title,
        description,
        price,
        category_id,
        image_url
      },
      message: '商品创建成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message,
      code: 500
    });
  }
});

// 更新商品（需要管理员权限）
router.put('/products/:id', isAdmin, upload.single('image'), (req, res) => {
  const { id } = req.params;
  const { title, description, price } = req.body;
  const image_url = req.file ? `/uploads/${req.file.filename}` : undefined;

  let query = 'UPDATE products SET title = ?, description = ?, price = ?';
  let params = [title, description, price];

  if (image_url) {
    query += ', image_url = ?';
    params.push(image_url);
  }

  query += ' WHERE id = ?';
  params.push(id);

  db.query(query, params, (error, results) => {
    if (error) {
      return res.status(500).json({ error: error.message });
    }
    if (results.affectedRows === 0) {
      return res.status(404).json({ message: '商品不存在' });
    }
    res.json({ message: '商品更新成功' });
  });
});

// 删除商品（需要管理员权限）
router.delete('/products/:id', isAdmin, (req, res) => {
  const { id } = req.params;
  db.query('DELETE FROM products WHERE id = ?', [id], (error, results) => {
    if (error) {
      return res.status(500).json({ error: error.message });
    }
    if (results.affectedRows === 0) {
      return res.status(404).json({ message: '商品不存在' });
    }
    res.json({ message: '商品删除成功' });
  });
});

// 搜索商品 - 移除认证要求
router.get('/products/search', async (req, res) => {
  try {
    const { q, category, min_price, max_price } = req.query;
    let query = `
      SELECT p.*, pc.name as category_name 
      FROM products p 
      LEFT JOIN product_categories pc ON p.category_id = pc.id 
      WHERE 1=1
    `;
    const params = [];

    if (q) {
      query += ' AND (p.title LIKE ? OR p.description LIKE ?)';
      params.push(`%${q}%`, `%${q}%`);
    }

    if (category) {
      query += ' AND p.category_id = ?';
      params.push(category);
    }

    if (min_price) {
      query += ' AND p.price >= ?';
      params.push(min_price);
    }

    if (max_price) {
      query += ' AND p.price <= ?';
      params.push(max_price);
    }

    query += ' ORDER BY p.created_at DESC';

    const [results] = await db.promise().query(query, params);

    res.json({
      success: true,
      data: results
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message,
      code: 500
    });
  }
});

// 获取商品列表（支持分页和排序）
router.get('/products/list', async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    const offset = (page - 1) * limit;
    const sort = req.query.sort || 'created_at';
    const order = req.query.order?.toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
    const category_id = req.query.category_id;

    // 构建查询条件
    let whereClause = '';
    const queryParams = [];
    if (category_id) {
      whereClause = 'WHERE p.category_id = ?';
      queryParams.push(category_id);
    }

    // 获取总数
    const [countResult] = await db.promise().query(
      `SELECT COUNT(*) as total FROM products p ${whereClause}`,
      queryParams
    );
    const total = countResult[0].total;

    // 获取商品列表
    const validSortFields = ['created_at', 'price', 'view_count'];
    const sortField = validSortFields.includes(sort) ? sort : 'created_at';

    const [products] = await db.promise().query(
      `SELECT p.*, c.name as category_name 
       FROM products p 
       LEFT JOIN product_categories c ON p.category_id = c.id 
       ${whereClause}
       ORDER BY p.${sortField} ${order}
       LIMIT ? OFFSET ?`,
      [...queryParams, limit, offset]
    );

    res.json({
      success: true,
      data: {
        items: products,
        pagination: {
          current_page: page,
          total_pages: Math.ceil(total / limit),
          total_items: total,
          per_page: limit
        }
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message,
      code: 500
    });
  }
});

// 获取商品详情（包含分类信息和相关推荐）- 移除认证要求
router.get('/products/:id/detail', async (req, res) => {
  try {
    const { id } = req.params;
    
    // 获取商品详情
    const [productResults] = await db.promise().query(`
      SELECT p.*, pc.name as category_name, pc.description as category_description
      FROM products p
      LEFT JOIN product_categories pc ON p.category_id = pc.id
      WHERE p.id = ?
    `, [id]);

    if (productResults.length === 0) {
      return res.status(404).json({
        success: false,
        error: '商品不存在',
        code: 404
      });
    }

    const product = productResults[0];
    
    // 获取相关推荐（同类别的其他商品）
    const [relatedResults] = await db.promise().query(`
      SELECT p.*
      FROM products p
      WHERE p.category_id = (SELECT category_id FROM products WHERE id = ?)
      AND p.id != ?
      LIMIT 5
    `, [id, id]);

    // 更新浏览量
    await db.promise().query(
      'UPDATE products SET view_count = view_count + 1 WHERE id = ?',
      [id]
    );
    
    res.json({
      success: true,
      data: {
        ...product,
        related_products: relatedResults
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message,
      code: 500
    });
  }
});

// 获取热门商品 - 移除认证要求
router.get('/products/hot', async (req, res) => {
  try {
    const limit = parseInt(req.query.limit) || 5;
    
    const [results] = await db.promise().query(`
      SELECT p.*, pc.name as category_name
      FROM products p
      LEFT JOIN product_categories pc ON p.category_id = pc.id
      ORDER BY p.view_count DESC
      LIMIT ?
    `, [limit]);

    res.json({
      success: true,
      data: results
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message,
      code: 500
    });
  }
});

// 创建商品 - 移除认证要求
router.post('/products', async (req, res) => {
  try {
    const { title, description, price, category_id, image_url } = req.body;

    // 基本验证
    if (!title || !price) {
      return res.status(400).json({
        success: false,
        error: '标题和价格为必填项',
        code: 400
      });
    }

    // 检查分类是否存在
    if (category_id) {
      const [category] = await db.promise().query(
        'SELECT id FROM product_categories WHERE id = ?',
        [category_id]
      );
      if (category.length === 0) {
        return res.status(400).json({
          success: false,
          error: '分类不存在',
          code: 400
        });
      }
    }

    const [result] = await db.promise().query(
      'INSERT INTO products (title, description, price, category_id, image_url) VALUES (?, ?, ?, ?, ?)',
      [title, description, price, category_id, image_url]
    );

    res.json({
      success: true,
      data: {
        id: result.insertId,
        title,
        description,
        price,
        category_id,
        image_url
      },
      message: '商品创建成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message,
      code: 500
    });
  }
});

module.exports = router; 